import React, {
  FC,
  useState,
  useEffect,
  useCallback,
  forwardRef,
  useImperativeHandle
} from 'react';
import { Spin, Tree } from 'antd';

import request from '@utils/request';
import notification from '@utils/notification';

import styles from './assignSubfunction.module.less';

interface AssignSubFunctionProps {
  /** 当前选择的id */
  currentId: number | string;

  /** ref */
  ref: any;
}

const AssignSubFunction: FC<AssignSubFunctionProps> = forwardRef(({ currentId }, ref) => {
  const [loading, setLoading] = useState<boolean>(false);

  const [treeData, setTreeData] = useState<any[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);

  /** 自定义暴露给父组件的ref属性 */
  useImperativeHandle(ref, () => ({
    queryTree: () => callbackHandleQueryTree(),
    saveTree: () => handleSaveTree()
  }));

  /** 查询数据 */
  const handleQueryTree = useCallback((id: any) => {
    setLoading(true);
    request({
      url: `/system/role/right/${id}`,
      method: 'GET'
    })
      .then((res: any) => {
        if (res) {
          const { tree = [], routeIds = [] } = res || {};
          setTreeData(tree);
          setCheckedKeys(routeIds);
          setExpandedKeys(routeIds);
          setAutoExpandParent(true);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  const callbackHandleQueryTree = useCallback(
    () => handleQueryTree(currentId),
    [currentId, handleQueryTree]
  );

  useEffect(() => {
    callbackHandleQueryTree();
  }, [callbackHandleQueryTree]);

  /** 树 展开|收起 */
  const onExpand = useCallback((expandedKeysValue: React.Key[]) => {
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  }, []);

  /** 树 勾选 */
  const onCheck = useCallback((checkedKeysValue: any) => {
    setCheckedKeys(checkedKeysValue);
  }, []);

  /** 菜单功能树保存 */
  const handleSaveTree = useCallback(() => {
    if (!currentId) return;

    setLoading(true);
    request({
      url: '/system/role/right',
      method: 'PUT',
      data: {
        roleId: currentId,
        routeIds: checkedKeys
      }
    })
      .then(async (res: any) => {
        if (res) {
          notification.success();
          // 查询最新数据
          callbackHandleQueryTree();
        }
      })
      .finally(() => {
        setLoading(false);
      });
  }, [callbackHandleQueryTree, currentId, checkedKeys]);

  return (
    <Spin spinning={loading}>
      <Tree
        checkable
        blockNode
        showLine
        className={styles.assignSubFunctionTree}
        selectable={false}
        treeData={treeData}
        key={treeData.length}
        onCheck={onCheck}
        checkedKeys={checkedKeys}
        onExpand={onExpand}
        expandedKeys={expandedKeys}
        autoExpandParent={autoExpandParent}
        fieldNames={{ title: 'name', key: 'id' }}
      />
    </Spin>
  );
});

export default AssignSubFunction;
